package com.tj.api.plugin;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;

@Plugin(name = "thread", category = StrLookup.CATEGORY)
public class ThreadLookup implements StrLookup {
    private Logger logger = LogManager.getLogger();

    @Override
    public String lookup(String key) {
        String env = getEnv();
        logger.info("loghub环境变量初始化,env:{}", env);
        setSysPorps(env);
        return Thread.currentThread().getName();
    }

    @Override
    public String lookup(LogEvent event, String key) {
        return event.getThreadName() == null ? Thread.currentThread().getName() : event
                .getThreadName();
    }

    private String getEnv() {
//        File envFile = new File("/opt/settings/server.properties");
//        String env = "PRO";//默认输出到线上
//        try {
//            List<String> list = Files.readLines(envFile, Charsets.UTF_8);
//            if (CollectionUtils.isNotEmpty(list)) {
//                env = list.get(0);
//                env = Splitter.on("=").omitEmptyStrings().splitToList(env).get(1);
//            }
//        } catch (Exception e) {
//            logger.error("env init failed", e);
//        }
//        return env;
        return null;
    }

    private void setSysPorps(String env) {
        if ("FAT".equals(env)) {
            setSysProp("projectName", "cashmama");
            setSysProp("logStore", "app-log-fat");
            setSysProp("topic", "binary-option");
            setSysProp("accessId", "LTAI8DgTTwCPs3eh");
            setSysProp("accessKey", "bbmzJd8OK3qPHgfv7zF2jRHoHZgEMx");
            setSysProp("endpoint", "ap-south-1-intranet.log.aliyuncs.com");

        }
        if ("PRO".equals(env) || "UAT".equals(env)) {
            setSysProp("projectName", "cashmama");
            setSysProp("logStore", "app-log");
            setSysProp("topic", "binary-option");
            setSysProp("accessId", "LTAI8DgTTwCPs3eh");
            setSysProp("accessKey", "bbmzJd8OK3qPHgfv7zF2jRHoHZgEMx");
            setSysProp("endpoint", "ap-south-1-intranet.log.aliyuncs.com");
        }
    }

    private void setSysProp(String key, String value) {
        if (StringUtils.isBlank(System.getProperty(key))) {
            System.setProperty(key, value);
        }
    }

}
